from datetime import datetime
from . import order_blue
from flask import render_template,jsonify,current_app,request,redirect,url_for,g
from info.utils.response_code import RET
from info.utils.response_code import error_map
from info.models import House, Area, Facility, Order
from info import db, constants
from info.utils.commons import login_required
from info.utils.image_storage import storage
from datetime import datetime

@order_blue.route('/api/v1.0/orders',methods=['POST','GET','PUT'])
@login_required
def orders():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == 'GET':
        role = request.args.get('role')

        if role not in ['custom','landlord']:
            return jsonify(errno=RET.PARAMERR,errmsg='数据不存在')

        if role == 'custom':
            try:
                orders = Order.query.filter(Order.user_id == user.id).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET,errmsg='')
            orders_list = []
            if orders:
                for item in orders:
                    orders_list.append(item.to_dict())
            data = {
                'orders':orders_list
            }
            return jsonify(errno=RET.OK, errmsg='OK',data=data)
        else:
            try:
                houses = House.query.filter(House.user_id == user.id).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='查询错误')
            house_id_list = []
            for item in houses:
                house_id_list.append(item.id)
            try:
                land_orders = Order.query.filter(Order.house_id.in_(house_id_list)).order_by(Order.status.desc()).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='数据库错误')

            land_orders_list = []
            if land_orders:
                for item in land_orders:
                    land_orders_list.append(item.to_dict())
            data = {
                'orders': land_orders_list
            }
            return jsonify(errno=RET.OK,errmsg='OK',data=data)

    if request.method == 'PUT':
        action = request.json.get('action')
        order_id = request.json.get('order_id')
        reason = request.json.get('reason',None)
        if not all([action,order_id]):
            return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
        try:
            order_id = int (order_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')
        if action not in ['accept','reject']:
            return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
        if action == 'accept':
            try:
                order = Order.query.get(order_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET,errmsg='')
            if not order:
                return jsonify(errno=RET.DATAERR,errmsg='订单不存在')
            order.status = 'WAIT_COMMENT'
            try:
                db.session.add(order)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
        else:
            try:
                order = Order.query.get(order_id)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg='订单不存在')
            if not reason:
                return jsonify(errno=RET.NODATA,errmsg='拒单理由缺失')
            order.status = 'REJECTED'
            order.comment = reason
            try:
                db.session.add(order)
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                db.session.rollback()
                return jsonify(errno=RET.DBERR,errmsg='保存数据失败')

        return jsonify(errno=RET.OK,errmsg='OK')





    house_id = request.json.get('house_id')
    start_date = request.json.get('start_date')
    end_date= request.json.get('end_date')

    if not all([house_id,start_date,end_date]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    try:
        start_date = datetime.strptime(start_date,'%Y-%m-%d')
        end_date = datetime.strptime(end_date,'%Y-%m-%d')
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数类型错误')
    if start_date>end_date or start_date==end_date:
        return jsonify(errno=RET.PARAMERR,errmsg='开始时间不能大于结束时间')
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库查询错误')

    if not house:
        return jsonify(errno=RET.NODATA,errmsg='房屋不存在')

    select_list = []
    # 按照时间查询房间
    conflict_order = None
    try:
        if start_date and end_date:
            conflict_order = Order.query.filter(Order.begin_date <= end_date, Order.end_date >= start_date).all()
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])
    if conflict_order:
        return jsonify(errno=RET.DATAEXIST,errmsg='订单以存在')
    try:
        days = (end_date - start_date).days
        amount = days * int(house.price)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')

    order = Order()
    order.user_id=user.id
    order.house_id=house_id
    order.begin_date=start_date
    order.end_date=end_date
    order.house_price=house.price
    order.days = days
    order.amount=amount
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    order_id = order.id
    data = {
        'order_id':order_id
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)



@order_blue.route('/api/v1.0/orders/comment',methods = ['PUT'])
@login_required
def comments():
    user = g.user
    if not user:
        return jsonify(errno=RET.LOGINERR,errmsg='用户未登录')
    comment = request.json.get('comment')
    order_id = request.json.get('order_id')
    if not all([comment,order_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    try:
        order_id=int(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='数据类型错误')
    try:
        order = Order.query.get(order_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')
    if not order:
        return jsonify(errno=RET.NODATA,errmsg='数据不存在')

    order.comment=comment
    order.status = 'COMPLETE'
    try:
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')

    return jsonify(errno=RET.OK,errmsg='OK')